import BaseModel from '@/editor/BaseModel';
import PluginManager, { PluginOptionMap, PluginMap } from '../PluginManager';
import * as THREE from 'three';
/**
 * 田地模型类，继承自 BaseModel
 * 生命周期
 * - 1.EVENT_BASEMODEL_LOADED (模型加载)
 * - 2.EVENT_BASEMODEL_PLUGINS_LOADED  (插件加载)
 *  @see {@link Editor.PlantAreaManager._manualEmitUpadateEvent}
 * - 2.1 若加载了PlantAreaManager插件 触发:EVENT_CROP_STAFF_UPDATE
 *
 *  @see {@link Editor.DeviceManager._manualEmitUpadateEvent}
 * - 2.2 若加载了DeviceManager插件 触发:EVENT_DEVICE_MANAGER_UPDATE
 *
 *  @see {@link Editor.RoadManager._manualEmitUpadateEvent}
 * - 2.3 若加载了RoadManager插件 触发:EVENT_ROAD_MANAGER_UPDATE
 */
export default class Field extends BaseModel {
  static type = 'field';

  id: number | string;

  /** FIXME: 后续优化 */
  url: string;

  pluginManager: PluginManager = null;

  constructor(option: Editor.FieldOption) {
    const { id = Date.now(), ...baseModelOption } = option;
    super(baseModelOption);
    this.id = id;
    this.on(BaseModel.EVENT_BASEMODEL_LOADED, (model: THREE.Object3D | null) => {
      if (model) {
        const { plugins, scene } = option;
        if (Array.isArray(plugins)) {
          plugins.forEach((plugin) => {
            const { name } = plugin;
            if (name === 'PlantAreaManager') {
              // 此时需要扩展builidng  +  scene
              const PlantAreaManagerOption = plugin.option as PluginOptionMap['PlantAreaManager'];
              const _option = Object.assign(PlantAreaManagerOption, {
                scene,
                building: this,
              }) as Editor.PlantAreaManagerOption;
              plugin.option = _option;
            }
          });
          this.pluginManager = new PluginManager(plugins);
          this.pluginManager.on(PluginManager.EVENT_PLUGINS_LOADED, (plugins) => {
            this._emitEvent(BaseModel.EVENT_BASEMODEL_PLUGINS_LOADED, plugins);
            Object.keys(plugins).forEach((pluginName: keyof PluginMap) => {
              const manager = this.getPluginByName(pluginName);
              manager._manualEmitUpadateEvent();
            });
          });
        }
      }
    });
  }

  /** 获取保存数据 */
  getSaveData(): Editor.FieldRenderData {
    return {
      id: this.id,
      url: this.url,
      scale: this.scale,
    };
  }

  /** 根据name获取对应插件manager */
  getPluginByName<T extends keyof PluginMap>(name: T): PluginMap[T] | null {
    if (!this.pluginManager) return null;
    const { plugins } = this.pluginManager;
    return plugins[name] as PluginMap[T];
  }
  destroy() {
    this.baseModelDispose();
  }
}
